package operatemodel

import (
	"errors"
	"server/global"
	"server/middleware"
	"server/model"

	"gorm.io/gorm"
)

func LoginAdmin(Username string, Password string) (code int, token string, role int) {
	var admin = &model.Admin{}
	d := model.DB.Where("username=? and password=?", Username, Password).First(admin)
	if errors.Is(d.Error, gorm.ErrRecordNotFound) {
		code = global.UorP_ERRO
		return
	} else if d.Error != nil {
		code = global.FAIL
		return
	}
	if admin.ID != 0 && admin.Username != "" {
		//生成token
		token2, code2 := middleware.CreateToken(admin.Username, admin.Role)
		if code2 != global.SUCCESS {
			token = ""
			code = code2
			role = 0
			return
		}
		code = code2
		token = token2
		role = admin.Role
		return
	}
	code = global.UorP_ERRO
	token = ""
	role = 0
	return
}

func Getalladmin() (data []model.Admin, code int) {
	d := model.DB.Find(&data)
	if d.RowsAffected == 0 {
		code = global.FAIL
		return
	} else if d.Error != nil {
		code = global.FAIL
		return
	}
	code = global.SUCCESS
	return
}

func Deleteadmin(id int) (code int) {
	d := model.DB.Delete(&model.Admin{}, id)
	if errors.Is(d.Error, gorm.ErrRecordNotFound) {
		code = global.FAIL
		return
	} else if d.Error != nil {
		code = global.FAIL
		return
	}
	code = global.SUCCESS
	return
}

func Addadmin(role int, username string, password string) (code int) {
	//gorm传入有数据的指令必须得是指针形式
	d := model.DB.Create(&model.Admin{Username: username, Password: password, Role: role})
	if d.Error != nil {
		code = global.FAIL
		return
	}
	code = global.SUCCESS
	return
}

func Updataadmin(role int, id int, newusername string, newpassword string) (code int) {
	d := model.DB.First(&model.Admin{}, id)
	//进行错误类型的判断-->查的时候用ErrRecordNotFound错误
	if errors.Is(d.Error, gorm.ErrRecordNotFound) {
		code = global.FAIL
		return
	} else if d.Error != nil {
		code = global.FAIL
		return
	}
	d = model.DB.Model(&model.Admin{}).Where("id=?", id).Updates(model.Admin{Username: newusername, Password: newpassword, Role: role})
	if errors.Is(d.Error, gorm.ErrRecordNotFound) {
		code = global.FAIL
		return
	} else if d.Error != nil {
		code = global.FAIL
		return
	}
	code = global.SUCCESS
	return
}
